//
//  AppStatusDidChangeEventProcessor.swift
//  app_rn_frontend
//
//  Created by 鱼涛 on 2017/12/13.
//  Copyright © 2017年 Facebook. All rights reserved.
//

import Foundation

class AppStatusDidChangeEventProcessor: EventProcessorProtocol {
  static let instance = AppStatusDidChangeEventProcessor()
  
  private init(){}
  
  func process(params: Dictionary<String, Any>?) throws{
    let isAppActive = AppStatusManager.instance.isAppActive
    let isUserLogin = AppStatusManager.instance.userLoginStatus.0
    let chatIp = AppStatusManager.instance.chatServerIp
    let syncTime = AppStatusManager.instance.syncTime ?? "1970-01-01 00:00:00"
    //let userId = AppStatusManager.instance.userLoginStatus.1

    let df = DateFormatter()
    df.dateFormat = "yyyy-MM-dd HH:mm:ss"
    let lastSyncTime = df.date(from: syncTime)
    let gregorian = NSCalendar(calendarIdentifier: NSCalendar.Identifier.gregorian)
    var result = gregorian!.components(NSCalendar.Unit.hour, from: lastSyncTime ?? df.date(from: "1970-01-01 00:00:00")!, to: Date(), options: NSCalendar.Options(rawValue: 0))
//    let nowString = "\(df.string(from: Date()))"
    
    if(isAppActive && isUserLogin ){

      if result.hour ?? 0 > 1 { //超过一小时，更新最新ip
        let urlPath: String = "\(AppStatusManager.instance.rnServer)im/getServerIp?userId=\(AppStatusManager.instance.userLoginStatus.1!)"
        let url = URL(string: urlPath)!
        var request = URLRequest(url: url)
        request.httpMethod = "GET"
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        let queue = OperationQueue()
      }else {
        if AppStatusManager.instance.chatServerIp == "" {
          return
        }
        ConnectionManager.instance.connect()
      }

    } else if !isAppActive  {
      ConnectionManager.instance.disconnect()
    }
  }
}
